<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('common.add') }}</el-button>
      <el-button :disabled="isButtonDisabled" class="filter-item" type="danger" icon="el-icon-delete" @click="deleteData" />
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :element-loading-text="$t('common.loading')"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column width="60px" type="selection" align="center" />

      <el-table-column :label="$t('common.sortNumber')" width="60px" type="index" align="center" />

      <el-table-column v-for="item in getTableList" :label="$t(''+item.label+'')" :prop="item.field" width="" align="center" default-sort sortable="custom">
        <template slot-scope="scope">
          <span>{{ scope.row[item.field] }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('common.description')" align="center">
        <template slot-scope="scope">
          <span class="link-type" style="justify-content: flex-start;">{{ scope.row.description != null ? scope.row.description : '' }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('common.handle')" width="180px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" style="margin:0;" @click="distribution(scope.row)">分配</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination :current-page="listQuery.pageNumber" :page-sizes="[2,20,30, 50]" :page-size="listQuery.pageSize" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!--添加和编辑-->
    <el-dialog :visible.sync="dialogFormVisible" title="角色添加/编辑">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" style="width: 400px; margin-left:50px;">

        <el-form-item :label="$t('common.name')" prop="name">
          <el-input v-model="temp.name" placeholder="角色名称" type="text" prefix-icon="el-icon-edit" clearable />
        </el-form-item>

        <el-form-item :label="$t('common.isEnabled')" prop="">
          <el-switch v-model="temp.isEnabled" active-text="是" inactive-text="否" />
        </el-form-item>

        <el-form-item :label="$t('common.description')" prop="description">
          <el-input v-model="temp.description" :autosize="{ minRows: 2, maxRows: 4}" :placeholder="$t('common.description')" type="textarea" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('common.cancel') }}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{ $t('common.confirm') }}</el-button>
        <el-button v-else type="primary" @click="updateData">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>

    <div v-if="permissionsFormVisible">
      <my-tree :permission-role="permissionRole" @cancel="cancel" />
    </div>

  </div>
</template>

<script>
import { fetchRoleList, saveRole, updateRole, grantPermission } from '@/api/system'
import waves from '@/directive/waves' // 水波纹指令
import myTree from './components/per-tree'
import { generalRemoveR } from '@/methods/apiGeneral' // 批量删除
import { codeValidation } from '@/methods/codeValidation'

export default {
  name: 'Role',
  directives: {
    waves
  },
  components: {
    myTree
  },
  data() {
    return {

      // 向筛选组件传入表头配置信息
      tableList: [
        {
          name: '名称',
          label: 'entity.system.name',
          field: 'name'
        },
        {
          // 组件显示的字段中文
          name: '类型',
          // 表格显示的名称
          label: 'entity.system.type',
          // 返回数据的字段
          field: 'typeT'
        },
        {
          name: '是否启用',
          label: 'entity.system.isEnabled',
          field: 'isEnabledT'
        }
      ],
      tableTitles: [
        { label: this.$t('entity.system.type'), value: 'type' },
        { label: this.$t('entity.system.name'), value: 'name' }
      ],
      getTableList: [
        {
          label: '名称',
          field: 'name'
        },
        {
          label: '是否启用',
          field: 'isEnabledVal'
        }
      ],

      // 分配權限的用戶ID和名字
      permissionRole: {
        roleId: '',
        roleName: ''
      },

      isButtonDisabled: true,
      pickingSetting: false,
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        pageNumber: 1,
        pageSize: 20
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [
        { label: this.$t('common.ascendingId'),
          key: '+id'
        },
        { label: this.$t('common.descendingId'),
          key: '-id'
        }
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: '',
        name: '',
        isEnabled: false,
        description: ''
      },
      permissions: {
        id: '',
        permissionIds: []
      },
      distributionName: '',
      dialogFormVisible: false,
      permissionsFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: this.$t('entity.area.edit'),
        create: this.$t('entity.area.add')
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [
          { required: true, message: this.$t('entity.area.name'), trigger: 'blur' }
        ],
        description: [{ min: 1, max: 255, message: this.$t('common.descriptionLength'), trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },

  created() {
    this.getList()
  },

  methods: {
    handleSearch() {
      var ids = { }
      ids[this.listQuery.item] = this.listQuery.content
      this.getRoleList(ids)
    },

    getList() {
      this.getRoleList(this.listQuery)
    },

    // 取消分配彈框
    cancel() {
      this.permissionsFormVisible = false
    },

    resetTemp() {
      this.temp = {
        id: '',
        name: '',
        isEnabled: false,
        description: ''
      }
    },

    // 获取用户列表
    getRoleList(data) {
      fetchRoleList(data).then(response => {
        var pageList = response.data.pageInfo.list // 内容
        pageList.forEach((value, index, array) => {
          value['typeT'] = D[value.type]
          value['isEnabledT'] = this.Util.nullToString(value, 'isEnabled')
        })
        var pageSize = this.listQuery.pageSize // 每页显示的条数
        var pageNumber = this.listQuery.pageNumber // 当前页码
        var total = response.data.pageInfo.total // 总共的条数
        this.Util.tableNumber(pageSize, pageNumber, total, pageList)

        pageList.forEach((item) => {
          if (item.isEnabled) {
            item['isEnabledVal'] = '是'
          } else {
            item['isEnabledVal'] = '否'
          }
        })
        this.list = pageList
        this.total = total
        this.listLoading = false
      })
    },

    createData() {
      var self = this
      saveRole(this.temp).then(response => {
        this.dialogFormVisible = false
        this.getRoleList()
        codeValidation('0', response.content, self)
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    updateData() {
      var self = this
      const tempData = Object.assign({}, this.temp)
      updateRole(tempData).then(response => {
        this.dialogFormVisible = false
        this.getRoleList()
        codeValidation('0', response.content, self)
      })
    },

    // 分配权限
    distribution(row) {
      // debugger
      this.permissionRole.roleId = row.id
      this.permissionRole.roleName = row.name
      this.permissionsFormVisible = true
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
      if (val.length === 0) {
        this.isButtonDisabled = true
      } else {
        this.isButtonDisabled = false
      }
    },

    // 批量删除
    deleteData() {
      var data = this.multipleSelection
      var location = 'role'
      var self = this
      generalRemoveR(data, location, self)
    },

    points() {
      this.permissions.permissionIds = this.permissions.permissionIds.toString()
      var self = this
      grantPermission(this.permissions).then(response => {
        codeValidation('0', response.content, self)
        this.permissionsFormVisible = false
        this.getRoleList()
      })
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    handleFilter() {
      this.listQuery.pageNumber = 1
      this.getRoleList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getRoleList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNumber = val
      this.getRoleList()
    }

  }
}
</script>

<style scoped>
  .filter-container{
    display:flex;
  }
  .filter-container .filter-item{
    margin-right:5px;
  }
  .el-button+.el-button.el-button--danger{
    margin:0 5px 10px 0;
  }
  .cell span{
    display:flex;
    justify-content: center;
  }
</style>
<style>
  .el-input-group>.el-input-group__prepend{
    width: 170px !important;
    height: 36px !important;
    padding: 0 !important;
  }
  .el-input-group .el-select .el-input.is-focus .el-input__inner {
    border-color: #f5f7fa !important;
  }
  .el-select .el-input .el-input__inner {
    padding:0 15px 0 10px;
  }
  .popper__arrow{
    left:60% !important;
  }
  .el-form-item__error{
    padding-top: 0px;
  }
  .el-form-item{
    margin-bottom:15px;
  }
  .form-item-content-flex .el-form-item__content{
    display:flex;
  }
</style>
